import Popup from "@/components/Popup/Popup";
import { defineComponent, reactive, ref } from "vue";
import styles from "./Add.module.less";
import RichEdit from "@/components/RichEdit/RichEdit.vue";
import to from "await-to-js";
import { $upload } from "@/apis/common/upload/upload";
import { message } from "ant-design-vue";

export default defineComponent({
  props: {
    service: {
      type: Object,
    }
  },
  emits: ['change'],
  setup(props, { expose, emit }) {
    const addPopupRef = ref(null as any);
    const formRef = ref(null as any);
    const adding = ref(false);
    const richEditRef = ref(null as any);
    const state = reactive({
      type: 'add',
      form: {
        id: null,
        name: null,
        content: '',
      },
      options: {
        pcid: [
          {
            label: '立式钢琴',
            value: 0,
          },
          {
            label: '智能钢琴',
            value: 1,
          },
          {
            label: '经典钢琴',
            value: 2,
          },
        ]
      }
    } as any);

    //url转blob
    const urlToBlob = async (url) => {
      try {
        const response = await fetch(url);
        const blob = await response.blob();
        return blob;
      } catch (error) {
        return null;
      }
    }
    
    //blob转字符串
    const blobToString = async (blob) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsText(blob);
      });
    }

    const getDetail = async () => {
      const [err, res]: any = await to(props.service?.detail(state.form.id))
      if (!err) {
        state.form.name = res?.data?.data?.name;
        let blob = await urlToBlob(res?.data?.data?.content);
        let content = await blobToString(blob);
        state.form.content = content || '';
      }
    }
    const submit = async () => {
      adding.value = true;
      const blob = new Blob([state.form.content], { type: "text/plain" })
      // 转换为 File 对象
      const file = new File([blob], "question.txt", {
        type: "text/plain",
        lastModified: new Date().getTime(),
      });
      const Form = new FormData();
      Form.append('file', file)
      const [errU, resU]: any = await to($upload(Form));
      if (errU) {
        return;
      }
      let str = resU?.data?.ossUpload?.fileUrl || '';
      let params: any = {
        name: state.form.name,
        content: str,
      }
      if (state.type === 'edit') {
        params.id = state.form.id
      }
      const [err, res]: any = await to((state.type === 'add' ? props.service?.add : props.service?.edit)(params))
      if (!err) {
        message.success('操作成功');
        emit('change');
        addPopupRef.value.close();
      }
      adding.value = false;
    }

    const open = async ({ type, id }) => {
      state.type = type;
      state.form.id = id;
      if (type === 'edit') {
        await getDetail()
      }
      addPopupRef.value.open();
      richEditRef?.value?.initValueHtml(
        state.form.content || ""
      );
    }

    expose({
      open,
    })
    return () => (
      <Popup
        ref={addPopupRef}
        title={state.type === 'add' ? '添加问题' : '编辑问题'}
        width="800px"
        oriState={state}
      >
        <div class={styles.container}>
          <div class={styles.formBox}>
            <a-form style={{ width: "100%" }} ref={formRef} model={state.form} label-col={{ style: { width: '130px', marginRight: '10px' } }} wrapper-col={{ span: 18 }}>
              <a-form-item required label="问题名称" name="name">
                <a-input v-model:value={state.form.name} placeholder="请输入问题名称" />
              </a-form-item>
              <a-form-item label="问题内容" name="content">
                <div class={styles.richEditBox}>
                  <RichEdit ref={richEditRef} v-model={state.form.content} />
                </div>
              </a-form-item>
            </a-form>
          </div>
          <div class={styles.footer}>
            <a-button type="primary" loading={adding.value} onClick={() => { submit() }}>确定</a-button>
            <a-button onClick={() => { addPopupRef.value.close() }} style={{ marginLeft: '20px' }}>取消</a-button>
          </div>
        </div>
      </Popup>
    )
  }
})